package com.isoftstone.merchant.controller.mprojecttype;

import com.isoftstone.bank.controller.base.BaseController;
import com.isoftstone.common.Tidings;
import com.isoftstone.merchant.entity.feeUser.MFeeUser;
import com.isoftstone.merchant.entity.mdept.MDept;
import com.isoftstone.merchant.entity.mproject.MProject;
import com.isoftstone.merchant.entity.mprojecttype.MProjectType;
import com.isoftstone.merchant.entity.payment.MPaymentDetail;
import com.isoftstone.merchant.entity.payment.Payment;
import com.isoftstone.merchant.entity.payment.PaymentMFee;
import com.isoftstone.merchant.service.feeUser.FeeUserService;
import com.isoftstone.merchant.service.mproject.MProjectService;
import com.isoftstone.merchant.service.mprojecttype.MProjectTypeService;
import com.isoftstone.merchant.service.payment.IMPaymentDetialService;
import com.isoftstone.merchant.service.payment.PaymentService;
import com.isoftstone.util.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by as on 2017/12/12.
 */
@Controller
public class BatchGeneratCostController extends BaseController {

    //项目收费类别
    @Autowired
    private MProjectTypeService mProjectTypeService;

    @Autowired
    private MProjectService mProjectService;

    @Autowired
    private FeeUserService feeUserService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private IMPaymentDetialService imPaymentDetialServicec;

    /*
    * 进入批量生成费用页面
    * */
    @RequiresPermissions("mms-menu.003.004")
    @RequestMapping("merchant/mProjectType/enterBatchGeneratCost")
    public ModelAndView toBatchGenerat(){
        ModelAndView md=new ModelAndView();
        md.setViewName("merchant/charge_management/handBatch_generat_cost");
        return md;
    }

    /*
    * 项目类型菜单回显
    * */
    @RequestMapping("merchant/mProjectType/getProjectTypeMenu")
    @ResponseBody
    public Object returnProjectType(){
        Tidings<Map> tidings = new Tidings<Map>();
        Map<String,Object> map = new HashMap<String,Object>();
        String status="1";
        map.put("corpId",this.getUser().getCorpId());
        map.put("status",status);
        List<MProjectType>typeList= null;
        try {
            typeList = mProjectTypeService.getTypeList(map);
            map.put("mProjectType",typeList);

            tidings.setT(map);
            tidings.setStatus(Const.SUCCESS);
            tidings.setMsg("查询成功！");
        }catch(Exception e){
            tidings.setStatus(Const.ERROR);
            tidings.setMsg("查询失败！");
            e.printStackTrace();
        }

        return tidings;
    }
    /*
    *根据项目类型选择项目名称
    * */
    @RequestMapping(value = "merchant/mProjectType/getProjectNameMenu",method = RequestMethod.POST)
    @ResponseBody
    public Object getProjectName(String projectTypeId){
        MProject m = new MProject();
        m.setProjectTypeId(Long.parseLong(projectTypeId));
        Tidings<Map> tidings = new Tidings<Map>();
        Map<String,Object> map = new HashMap<String,Object>();
        try{
            List<MProject> mProject = mProjectService.findProjectNameList(m.getProjectTypeId());
            map.put("mProject",mProject);
            tidings.setT(map);
            tidings.setStatus(Const.SUCCESS);
            tidings.setMsg("查询成功！");
        }catch(Exception e){
            tidings.setStatus(Const.ERROR);
            tidings.setMsg("查询失败！");
            e.printStackTrace();
        }
        return tidings;
    }

    /*
    * 下载模板
    * */
    @RequestMapping("merchant/mProjectType/getBatchExcelModel")
    public ModelAndView getExcelModel(){
        ModelAndView mv = new ModelAndView();
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> titles = new ArrayList<String>();
        titles.add("缴费编号");
        titles.add("缴费金额");
        map.put("titles", titles);
        PageData pd = new PageData();
        pd.put("var1", "");
        pd.put("var2", "");
        List<PageData> list = new ArrayList<PageData>();
        list.add(pd);
        map.put("varList", list);
        map.put("name", "startPayment");
        map.put("sheetName", "批量生成费用");
        ObjectExcelView erv = new ObjectExcelView();
        mv = new ModelAndView(erv, map);
        return mv;
    }

    /*
    * 发起缴费
    * @param file 上传文件
    * @param projectTypeId 项目类型id
    * @param projectId 项目名称id
    * */
    @RequestMapping(value="merchant/mProjectType/initiatePayment",method = RequestMethod.POST,produces = {"text/html;charset=UTF-8"})
    // @ResponseBody
    public void initiatePayment(@RequestParam(value = "file", required = false) MultipartFile file,
                                String selectProjectType, String selectCostName, HttpServletRequest request, HttpServletResponse response){
        String projectType = selectProjectType;
        String projectName = selectCostName;
        Tidings<String> tidings = new Tidings<String>();
        String userId=this.getUser().getUserid();
        List<Tidings>list1=new ArrayList<Tidings>();
        this.getResponse().setContentType("text/html;charset=UTF-8");
        String filePath = PathUtil.getClasspath() + Const.FILEPATHFILE;//保存文件路径
        String generatorFileName = UuidUtil.get32UUID();//生成文件名
        Map<String, Object> map = new HashMap<String, Object>();
        String cropId = this.getUser().getCorpId();
        String filename = null;
        try {
            System.out.println("文件大小：" + file.getSize());
            filename = FileUpload.fileUp(file, filePath, generatorFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String header = "缴费编号:feeId,缴费金额:totalAmt";
        List<MDept>deptids=null;
        Map<String,Object>map1=new HashMap<String,Object>();
        try {
            deptids=feeUserService.getalldeptByUserId(userId);//得到用户对应的deptid
            if(deptids!=null){
                List<String>list=new ArrayList<String>();
                for(MDept mDept1:deptids){
                    list.add(mDept1.getDeptId());
                }
                map1.put("deptIds",list);//看到当前用户部门的缴费用户
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try{
            System.out.println("filename = " + filename);
            List<PaymentMFee> pms = ExcelUtil.readXls(filePath + filename, ExcelUtil.getMap(header), "com.isoftstone.merchant.entity.payment.PaymentMFee");
            logger.info(pms.size());
            if(pms.size()>0){
            for (int i = 0; i < pms.size(); i++) {
                PaymentMFee paymentMFee = pms.get(i);
                if (XSSCheckUtil.checkXSS(paymentMFee.getFeeId()) || XSSCheckUtil.checkXSS(paymentMFee.getTotalAmt())){
                    tidings.setStatus(Const.ERROR);
                    tidings.setMsg("第" + (i + 1) + "行导入内容不合法");
                    throw new RuntimeException("第" + (i + 1) + "行导入内容不合法");
                }
            }

            int i = 0;
            List<PaymentMFee> paymentMFees = new ArrayList<PaymentMFee>();
            for(PaymentMFee p : pms){
                PaymentMFee pMFee = new PaymentMFee();
                if (StringUtils.isBlank(p.getFeeId())) {
                    tidings.setStatus(Const.ERROR);
                    tidings.setMsg("第" + (i + 2) + "行缴费编号不能为空");
                    throw new RuntimeException("第" + (i + 2) + "行缴费编号不能为空");
                } else {
                    map1.put("feeId",p.getFeeId());
                    Integer mf = feeUserService.getFeeUserId1(map1);//查询缴费编号是否存在
                    if (mf != 0) {
                        pMFee.setFeeId(p.getFeeId());
                    } else {
                        tidings.setStatus(Const.ERROR);
                        tidings.setMsg("第" + (i + 2) + "行缴费编号"+ p.getFeeId() +"不存在");
                        throw new RuntimeException("第" + (i + 2) + "行缴费编号"+ p.getFeeId() +"不存在");
                    }
                }

                if(StringUtils.isBlank(p.getTotalAmt().toString())){
                    tidings.setStatus(Const.ERROR);
                    tidings.setMsg("第" + (i + 2) + "行缴费金额不能为空");
                    throw new RuntimeException("第" + (i + 2) + "行缴费金额不能为空");
                }else{
                    pMFee.setTotalAmt(p.getTotalAmt());
                }
                paymentMFees.add(pMFee);
            }
            if (paymentMFees.size()>0) {
                for (PaymentMFee pmf : paymentMFees) {
                    //先根据缴费编号查询m_fee_user表中的缴费用户id:FEE_USER_ID
                    MFeeUser mFeeUser = new MFeeUser();
                    mFeeUser.setFeeId(pmf.getFeeId());
                    mFeeUser.setCorpId(this.getUser().getCorpId());
                    //String feeUsrId = feeUserService.findFeeUserIdByFeeId(mFeeUser.getFeeId());
                    String feeUsrId = feeUserService.findFeeUserIdByFeeId(mFeeUser);
                    //新增查询出来的id和缴费金额到到表m_payment_main中,并返回当前插入的id:payment.getPayId()
                    Payment payment = new Payment();
                    payment.setFeeUserId(feeUsrId);
                    payment.setTotalAmt(Double.parseDouble(pmf.getTotalAmt()));
                    payment.setUrgeCnt(0);
                    payment.setPayStatus("04");
                    payment.setCreateDate(new Date());
                    payment.setStatus("1");
                    payment.setCreator(this.getUser().getUserid());
                    paymentService.addPaymentToBatch(payment);
                   // System.out.println("批量生成费用返回第"+(i+1)+"个ID = " + payment.getPayId());
                    //继续新增到表m_payment_detail中，参数，上面新增的id，项目类型id
                    MPaymentDetail mPaymentDetail = new MPaymentDetail();
                    mPaymentDetail.setPayId(payment.getPayId());
                    mPaymentDetail.setProjectId(Long.parseLong(projectName));
                    mPaymentDetail.setTotalAmt(Double.parseDouble(pmf.getTotalAmt()));
                    mPaymentDetail.setRemark("");
                    imPaymentDetialServicec.addPaymentDetail(mPaymentDetail);
                }
                tidings.setStatus(Const.SUCCESS);
                tidings.setMsg("成功发起缴费"+paymentMFees.size()+"条");
            }
            }else{
                tidings.setStatus(Const.ERROR);
                tidings.setMsg("请填写数据");
                throw new RuntimeException("请填写数据");
            }
        }catch(Exception e){
            e.printStackTrace();
            if(tidings.getStatus()==null){
                tidings.setStatus(Const.ERROR);
                tidings.setMsg("缴费失败,请按照模板填写数据");
            }
        }

        list1.add(tidings);
        try {
            this.getResponse().getWriter().write(JsonUtil.writeListJSON(list1));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
